//
//  ActionSheet.m
//  KKMY2_U
//
//  Created by 黄磊 on 14-5-25.
//  Copyright (c) 2014年 jiulong.zhou. All rights reserved.
//

#import "ActionSheet.h"


#define ActionSheetPopupDuration 0.3

#define ActionSheetMinHeight 124
#define ActionSheetTitleHeight 22
#define ActionSheetContentMinHeight 30
#define ActionSheetButtonHeight 44
#define ActionSheetButtonWidth 286
#define ActionSheetGapBetweenButton 15
#define ActionSheetPaddingLeft 17

@class ActionSheet;
@class WindowActionSheet;

static WindowActionSheet *g_actionSheetWindow = nil;
static NSMutableArray *g_arrActionSheet = nil;



@interface WindowActionSheet : UIWindow

@property (nonatomic, assign) BOOL windowWillHide;

- (void)showActionSheetWindowCompletion:(void (^)(BOOL finished))completion;
- (void)hideActionSheetWindowCompletion:(void (^)(BOOL finished))completion;

@end



@interface ActionSheet ()
@property (weak, nonatomic) IBOutlet UIImageView *bgImageView;

@property (strong, nonatomic) IBOutlet UILabel *lblTitle;
@property (strong, nonatomic) IBOutlet UIView *viewContent;
@property (strong, nonatomic) IBOutlet UIView *viewButtons;
@property (strong, nonatomic) IBOutlet UIButton *btnCancel;
@property (strong, nonatomic) NSMutableArray *buttons;

- (WindowActionSheet *)actionSheetWindow;
+ (NSMutableArray *)arrActionSheet;

- (void)fadeOutAnimated:(BOOL)animated completion:(void (^)(BOOL finished))completion;

@end



@implementation WindowActionSheet


- (void)windowsTap
{
    if (_windowWillHide) {
        return;
    }
    _windowWillHide = YES;
    NSMutableArray *arrActionSheet = [ActionSheet arrActionSheet];
    if ([arrActionSheet count] > 0) {
        ActionSheet *nextActionSheet = [arrActionSheet lastObject];
        if ([nextActionSheet isInShow]) {
            [nextActionSheet fadeOutAnimated:YES completion:^(BOOL finished)
            {
                for (ActionSheet *aActionSheet in arrActionSheet) {
                    [aActionSheet removeFromSuperview];
                }
                [arrActionSheet removeAllObjects];
            }];
        }
    }
    
    
    [self hideActionSheetWindowCompletion:nil];
}



- (void)showActionSheetWindowCompletion:(void (^)(BOOL finished))completion
{
    if ([self isHidden]) {
        //        self.actionSheetWindow.alpha = 0.0;
        UIImageView *imgviewBg = [self.subviews objectAtIndex:0];
        imgviewBg.alpha = 0.0;
        [self makeKeyAndVisible];
        [self setHidden:NO];
        [UIView animateWithDuration:0.2 animations:^
         {
             imgviewBg.alpha = 1.0;
         }
                         completion:^(BOOL finished)
         {
             if (completion) {
                 completion(finished);
             }
         }];
    } else {
        if (completion) {
            completion(YES);
        }
    }
}

- (void)hideActionSheetWindowCompletion:(void (^)(BOOL finished))completion
{
    [UIView animateWithDuration:0.2 animations:^
     {
         UIImageView *imgviewBg = [self.subviews objectAtIndex:0];
         imgviewBg.alpha = 0.0;
     }
                     completion:^(BOOL finished)
     {
         [self setHidden:YES];
         [self resignKeyWindow];
         [self setHidden:YES];
         g_actionSheetWindow = nil;
         if (completion) {
             completion(finished);
         }
     }];
}


@end

@implementation ActionSheet

- (id)initWithFrame:(CGRect)frame
{
    
    self = (ActionSheet *)[[[NSBundle mainBundle] loadNibNamed:@"ActionSheet"
                                                         owner:self
                                                       options:nil] objectAtIndex:0];
    if (self) {
        // Initialization code
        [self dataConfig];
    }
    return self;
}

- (id)initWithTitle:(NSString *)title delegate:(id<ActionSheetDelegate>)delegate cancelButtonTitle:(NSString *)cancelButtonTitle destructiveButtonTitle:(NSString *)destructiveButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ...
{
    self = [self initWithFrame:CGRectZero];
    if (self) {
        _title = title;
        _delegate = delegate;
        
        [_lblTitle setText:title];
        _btnCancel.layer.cornerRadius = 5;
        if (cancelButtonTitle.length > 0) {
            [_btnCancel setTitle:cancelButtonTitle forState:UIControlStateNormal];
            [_btnCancel addTarget:self action:@selector(buttonOnClick:) forControlEvents:UIControlEventTouchUpInside];
        } else {
            [_viewContent setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin];
            [_btnCancel setHidden:YES];
            CGRect rect = self.frame;
            rect.size.height -= (ActionSheetButtonHeight + ActionSheetGapBetweenButton);
            self.frame = rect;
            [_viewContent setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
        }
        
        // 添加其他button
        va_list arguments;
        id eachButtonTitle;
        if (otherButtonTitles) {
            va_start(arguments, otherButtonTitles);
            [self addButtonWithTitle:otherButtonTitles];
            while ((eachButtonTitle = va_arg(arguments, id))) {
                [self addButtonWithTitle:(NSString *)eachButtonTitle];
            }
            va_end(arguments);
        }
        
        if (destructiveButtonTitle.length > 0) {
            [self addDestructiveButtonWithTitle:destructiveButtonTitle];
        }
    }
    return self;
}


- (id)initWithTitle:(NSString *)title delegate:(id<ActionSheetDelegate>)delegate cancelButtonTitle:(NSString *)cancelButtonTitle viewCustom:(UIView *)viewCustom otherButtonTitles:(NSString *)otherButtonTitles, ...
{
    self =  [self initWithTitle:title delegate:delegate cancelButtonTitle:cancelButtonTitle destructiveButtonTitle:nil otherButtonTitles:nil];
    if (self) {
        
        // 添加其他button
        va_list arguments;
        id eachButtonTitle;
        if (otherButtonTitles) {
            va_start(arguments, otherButtonTitles);
            [self addButtonWithTitle:otherButtonTitles];
            while ((eachButtonTitle = va_arg(arguments, id))) {
                [self addButtonWithTitle:(NSString *)eachButtonTitle];
            }
            va_end(arguments);
        }
        
        [self setViewCustom:viewCustom];
    }
    return self;
}

- (WindowActionSheet *)actionSheetWindow
{
    if (g_actionSheetWindow == nil) {
        CGRect screenRect = [[UIScreen mainScreen] bounds];
        g_actionSheetWindow = [[WindowActionSheet alloc] initWithFrame:screenRect];
        g_actionSheetWindow.windowLevel = UIWindowLevelAlert;
        g_actionSheetWindow.windowWillHide = NO;
        g_actionSheetWindow.backgroundColor = [UIColor clearColor];
        // 初始化弹窗window
        UIImage *imgBg = [UIImage createImageWithColor:[[UIColor blackColor] colorWithAlphaComponent:0.5]];
        UIImageView *imgviewBg = [[UIImageView alloc] initWithImage:imgBg];
        [imgviewBg setFrame:screenRect];
        [imgviewBg setUserInteractionEnabled:YES];
        
//        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressed:)];
//        [imgviewBg addGestureRecognizer:longPress];
        
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:g_actionSheetWindow action:@selector(windowsTap)];
        [imgviewBg addGestureRecognizer:tapGesture];

        [g_actionSheetWindow addSubview:imgviewBg];
//        [g_alertView makeKeyWindow];
//        [g_alertView setHidden:YES];
    }
    return g_actionSheetWindow;
}

+ (NSMutableArray *)arrActionSheet
{
    if (g_arrActionSheet == nil) {
        g_arrActionSheet = [[NSMutableArray alloc] init];
    }
    return g_arrActionSheet;
}

- (void)viewConfig
{
    
}

- (void)dataConfig
{
    _buttons = [[NSMutableArray alloc] init];
    _numberOfButtons = 0;
    _viewCustom = nil;
    _isInShow = NO;
}

- (void)setViewCustom:(UIView *)viewCustom
{
    if (viewCustom == nil) {
        return;
    }
    CGFloat height = viewCustom.frame.size.height;
    if (_viewCustom) {
        height -= (_viewCustom.frame.size.height - ActionSheetGapBetweenButton);
        [_viewCustom removeFromSuperview];
    }
    CGRect rect = viewCustom.frame;
    if (rect.size.width > kScreenWidth) {
        rect.size.width = kScreenWidth;
    }
    rect.origin.x = (kScreenWidth - rect.size.width) / 2;
    rect.origin.y = ActionSheetGapBetweenButton;
    [viewCustom setFrame:rect];
    _viewCustom = viewCustom;
    [_viewButtons setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin];
    [_viewCustom setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin];
    [_viewContent addSubview:_viewCustom];
    CGRect rectSelf = self.frame;
    rectSelf.size.height += (height + ActionSheetGapBetweenButton);
    [self setFrame:rectSelf];
    [_viewButtons setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
}

#pragma mark - Public


- (void)show
{
    
    [self.actionSheetWindow showActionSheetWindowCompletion:^(BOOL finished) {}];
    NSArray *arrActionSheet = [ActionSheet arrActionSheet];
    if ([arrActionSheet count] > 0) {
        ActionSheet *nextActionSheet = [arrActionSheet lastObject];
        if ([nextActionSheet isInShow]) {
            [nextActionSheet fadeOutAnimated:YES completion:^(BOOL finished) {}];
        }
    }
    [self setHidden:YES];
    [self.actionSheetWindow addSubview:self];
    [[ActionSheet arrActionSheet] addObject:self];
    [self popupCompletion:^(BOOL finished) {}];
    
}



- (NSInteger)addButtonWithTitle:(NSString *)title
{
    UIButton *aBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, _viewButtons.frame.size.height, ActionSheetButtonWidth, ActionSheetButtonHeight)];
    [aBtn setBackgroundColor:kAppActiveColor];
    [aBtn setTitle:title forState:UIControlStateNormal];
    [aBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [aBtn setTag:_numberOfButtons];
    [aBtn addTarget:self action:@selector(buttonOnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [_buttons addObject:aBtn];
    [_viewButtons addSubview:aBtn];
    
    CGRect rect = self.frame;
    rect.size.height += (ActionSheetButtonHeight + ActionSheetGapBetweenButton);
    self.frame = rect;
    
    return _numberOfButtons++;
}


- (NSString *)buttonTitleAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex > _buttons.count - 1) {
        if (buttonIndex < 0) {
            if (buttonIndex == -1) {
                return _btnCancel.titleLabel.text;
            }
            return nil;
        }
        UIButton *aBtn = [_buttons objectAtIndex:buttonIndex];
        return aBtn.titleLabel.text;
    }
    return nil;
}

-(void)hideOtherControls{
    self.bgImageView.hidden=YES;
    self.bgImageView.frame=CGRectZero;
    self.lblTitle.hidden=YES;
    self.lblTitle.frame=CGRectZero;
    self.viewButtons.hidden=YES;
    self.viewButtons.frame=CGRectZero;
    self.btnCancel.hidden=YES;
    self.btnCancel.frame=CGRectZero;
}


#pragma mark - Action

- (void)buttonOnClick:(id)sender
{
    UIButton *aBtn = (UIButton *)sender;
    [self dismissWithClickedButtonIndex:aBtn.tag animated:YES];
}

- (void)longPressed:(UIGestureRecognizer*)gestureRecognizer
{
    
}


#pragma mark - Private


- (void)addDestructiveButtonWithTitle:(NSString *)title
{
    _destructiveButtonIndex = [self addButtonWithTitle:title];
    UIButton *aBtn = [_buttons lastObject];
    [aBtn setBackgroundImage:[UIImage createImageWithColor:[UIColor redColor]] forState:UIControlStateNormal];
}


- (void)dismissWithClickedButtonIndex:(NSInteger)buttonIndex animated:(BOOL)animated;
{
    _isInShow = NO;
    if (_delegate != nil && [_delegate respondsToSelector:@selector(actionSheet:clickedButtonAtIndex:)]) {
        [_delegate actionSheet:self clickedButtonAtIndex:buttonIndex];
    }
    if (_delegate != nil && [_delegate respondsToSelector:@selector(actionSheet:willDismissWithButtonIndex:)]) {
        [_delegate actionSheet:self willDismissWithButtonIndex:buttonIndex];
    }
    [self fadeOutAnimated:animated completion:^(BOOL finished) {
        [self removeFromSuperview];
        [[ActionSheet arrActionSheet] removeObject:self];
        if (_delegate != nil && [_delegate respondsToSelector:@selector(actionSheet:didDismissWithButtonIndex:)]) {
            [_delegate actionSheet:self didDismissWithButtonIndex:buttonIndex];
        }
    }];
    [self doCleanUp];
}


- (void)doCleanUp
{
    
    _isInShow = NO;
    
    NSArray *arrActionSheet = [ActionSheet arrActionSheet];
    if ([arrActionSheet count] > 1) {
        ActionSheet *lastActionSheet = [arrActionSheet lastObject];
        if ([lastActionSheet isEqual:self]) {
            ActionSheet *nextActionSheet = [arrActionSheet objectAtIndex:arrActionSheet.count - 2];
            [nextActionSheet rePopup];
        } else {
            if (![lastActionSheet isInShow]) {
                [lastActionSheet rePopup];
            }
        }
        
    } else {
        [self.actionSheetWindow hideActionSheetWindowCompletion:nil];
    }
}

#pragma mark - Animate





- (void)popupCompletion:(void (^)(BOOL finished))completion
{
    _isInShow = YES;
    if (_delegate != nil && [_delegate respondsToSelector:@selector(willPresentActionSheet:)]) {
        [_delegate willPresentActionSheet:self];
    }
    CGRect rect = self.frame;
    CGRect rectWindow = self.actionSheetWindow.frame;
    rect.origin.y = rectWindow.size.height;
    [self setFrame:rect];
    [self setHidden:NO];
    [UIView animateWithDuration:ActionSheetPopupDuration animations:^{
        CGRect rect = self.frame;
        CGRect rectWindow = self.actionSheetWindow.frame;
        rect.origin.y = rectWindow.size.height - rect.size.height;
        [self setFrame:rect];
    } completion:^(BOOL finished) {
        if (_delegate != nil && [_delegate respondsToSelector:@selector(didPresentActionSheet:)]) {
            [_delegate didPresentActionSheet:self];
        }
        if (completion) {
            completion(finished);
        }
    }];

}

- (void)fadeOutAnimated:(BOOL)animated completion:(void (^)(BOOL finished))completion
{
    if (animated) {
        [UIView animateWithDuration:ActionSheetPopupDuration animations:^ {
            CGRect rect = self.frame;
            CGRect rectWindow = self.actionSheetWindow.frame;
            rect.origin.y = rectWindow.size.height;
            [self setFrame:rect];
        } completion:^(BOOL finished) {
            if (completion) {
                completion(finished);
            }
        }];
    } else {
        if (completion) {
            completion(YES);
        }
    }
}

- (void)rePopup
{
    [self.actionSheetWindow bringSubviewToFront:self];
    [self popupCompletion:^(BOOL finished) {}];
}

- (void)startLoading:(NSString *)labelText
{
    if(labelText == nil || [labelText isEqualToString:@""])
    {
        labelText = @"加载中...";
    }
    [[MBProgressHUD showHUDAddedTo:self animated:YES] setLabelText:labelText];
}

- (void)stopLoading
{
    [MBProgressHUD hideAllHUDsForView:self animated:YES];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
